package com.onion.mvc.resolver;

import com.onion.mvc.annotation.OnionParam;
import com.onion.mvc.enums.ParamPolicy;
import com.onion.mvc.resolver.builder.*;
import com.onion.utils.surface.request.Request;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.security.Policy;
import java.util.HashMap;
import java.util.Map;

public class RequestParamResolver implements HandlerMethodArgumentResolver {

    private String KEY_PAGE_NO = "pageNo";
    private String KEY_PAGE_SIZE = "pageSize";
    private int defaultPageSize = 15;

    private Map<ParamPolicy, RequestParamBuilder> requestParamBuilderMap = new HashMap<>();

    public void initEvent(){
        requestParamBuilderMap.put(ParamPolicy.BODY_ONLY, new BodyOnlyParamBuilder());
        requestParamBuilderMap.put(ParamPolicy.BODY_PRIOR, new BodyPriorParamBuilder());
        requestParamBuilderMap.put(ParamPolicy.PARAM_ONLY, new ParamOnlyParamBuilder());
        requestParamBuilderMap.put(ParamPolicy.PARAM_PRIOR, new ParamPriorParamBuilder());
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(OnionParam.class) &&
                Request.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        OnionParam onionParam = parameter.getParameterAnnotation(OnionParam.class);
        return requestParamBuilderMap.get(onionParam.policy()).build(webRequest, parameter);
    }

}